<template>
  <div class="statistics-container">
    <!-- 头部信息和选项卡 -->
    <div class="header-section">
      <div class="roll-info">
        <span class="roll-label">卷号</span>
        <el-input v-model="currentRollNo" placeholder="请输入卷号" class="roll-input" />
        <button class="btn analysis-btn">分析</button>
      </div>
      <el-tabs v-model="activeTab" class="analysis-tabs">
        <el-tab-pane label="厚度质量分析" name="thickness"></el-tab-pane>
        <el-tab-pane label="板形质量分析" name="shape"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 主要内容区域 (基于选项卡切换，此处先展示板形分析) -->
    <div v-if="activeTab === 'shape'" class="main-content">
      <!-- 左侧面板: 品规工艺分析 -->
      <div class="panel left-panel">
        <div class="panel-header">
          <span class="panel-title">品规工艺分析</span>
          <span class="panel-subtitle">板形 风险因子排名</span>
        </div>
        <div class="panel-body">
          <div class="gauge-charts-row">
            <div ref="gaugeChart1Ref" class="gauge-chart-container"></div>
            <div ref="gaugeChart2Ref" class="gauge-chart-container"></div>
            <div ref="gaugeChart3Ref" class="gauge-chart-container"></div>
            <div ref="gaugeChart4Ref" class="gauge-chart-container"></div>
          </div>
          <div class="reason-text">
            <span class="reason-label">原因类型:</span> {{ riskReasonText }}
          </div>
          <div class="table-container">
            <el-table :data="riskFactorData" style="width: 100%" border size="small">
              <el-table-column prop="name" label="名称" />
              <el-table-column prop="chineseName" label="名称中文" />
              <el-table-column prop="riskFactor" label="风险系数" align="center"/>
              <el-table-column prop="recommendedRange" label="推荐区间" align="center"/>
              <el-table-column prop="currentValue" label="当前值" align="center"/>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 右侧面板: 单卷工艺分析 -->
      <div class="panel right-panel">
         <div class="panel-header">
          <span class="panel-title">单卷工艺分析</span>
          <span class="panel-subtitle">头部</span> 
        </div>
         <div class="panel-body">
           <div class="gauge-charts-row">
            <div ref="gaugeChart5Ref" class="gauge-chart-container"></div>
            <div ref="gaugeChart6Ref" class="gauge-chart-container"></div>
            <div ref="gaugeChart7Ref" class="gauge-chart-container"></div>
            <div ref="gaugeChart8Ref" class="gauge-chart-container"></div>
          </div>
           <div class="reason-text">
            <span class="reason-label">原因类型:</span> {{ singleCoilReasonText }}
          </div>
           <div class="chart-container-large" ref="lineBarChartRef">
             <!-- Complex Chart Placeholder -->
          </div>
        </div>
      </div>
    </div>
    <!-- Placeholder for thickness analysis tab -->
     <div v-else class="main-content-placeholder">
        厚度质量分析内容待添加...
     </div>

  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import * as echarts from 'echarts/core';
import {
  GaugeChart, 
  LineChart,
  BarChart // For potential bar series in the complex chart
} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent,
  MarkLineComponent // Added for the complex chart limits
} from 'echarts/components';
import {
  CanvasRenderer
} from 'echarts/renderers';

// Register ECharts components
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  GaugeChart, 
  LineChart,
  BarChart,
  CanvasRenderer,
  DataZoomComponent,
  MarkLineComponent 
]);

// --- State --- 
const currentRollNo = ref('L12501197700');
const activeTab = ref('shape'); // Default to shape analysis tab

// --- Mock Data --- 
// Left Panel
const riskReasonText = ref('4机架辊缝中部均值偏小, 5机架工作辊操作侧弯辊力尾部均值偏大, 4机架辊缝头部均值偏小');
const riskFactorData = ref([
  { name: 'S4_ROLLGAP_MID_AVG_score', chineseName: '4机架辊缝中部均值', riskFactor: 26, recommendedRange: '-2.59~-0.01', currentValue: -3.29 },
  { name: 'S5_WR_BENDFORCE_OS_TAIL_AV E_score', chineseName: '5机架工作辊操作侧弯辊力尾部均值', riskFactor: 25, recommendedRange: '8.05~16.11', currentValue: 7.39 },
  { name: 'S4_ROLLGAP_TAIL_AVG_score', chineseName: '4机架辊缝尾部均值', riskFactor: 25, recommendedRange: '-2.75~-0.1', currentValue: -3.41 },
  { name: 'S4_ROLLGAP_HEAD_AVG_score', chineseName: '4机架辊缝头部均值', riskFactor: 24, recommendedRange: '-2.71~-0.1', currentValue: -3.36 },
]);
const gaugeValuesLeft = ref([26, 25, 25, 24]);

// Right Panel
const singleCoilReasonText = ref('热轧卷取温度, 热轧终轧温度, 3机架上中间辊窜辊实际, S2机架轧制力差DS-OS');
const gaugeValuesRight = ref([78.26, 78.22, 72.33, 71.73]);

// --- ECharts Refs --- 
const gaugeChart1Ref = ref<HTMLElement | null>(null);
const gaugeChart2Ref = ref<HTMLElement | null>(null);
const gaugeChart3Ref = ref<HTMLElement | null>(null);
const gaugeChart4Ref = ref<HTMLElement | null>(null);
const gaugeChart5Ref = ref<HTMLElement | null>(null);
const gaugeChart6Ref = ref<HTMLElement | null>(null);
const gaugeChart7Ref = ref<HTMLElement | null>(null);
const gaugeChart8Ref = ref<HTMLElement | null>(null);
const lineBarChartRef = ref<HTMLElement | null>(null);

// --- ECharts Instances --- 
let gaugeInstances: echarts.ECharts[] = [];
let lineBarChartInstance: echarts.ECharts | null = null;

// --- ECharts Options --- 
const createGaugeOption = (value: number) => ({
    series: [
        {
            type: 'gauge',
            center: ['50%', '60%'],
            radius: '90%',
            startAngle: 200,
            endAngle: -20,
            min: 0,
            max: 100,
            splitNumber: 5,
            progress: {
                show: true,
                width: 12,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                      { offset: 0, color: '#58D6F8' },
                      { offset: 1, color: '#2AF598' }
                  ])
                }
            },
            pointer: { show: false },
            axisLine: {
                lineStyle: {
                    width: 12,
                     color: [[1, '#2c3e50']]
                }
            },
            axisTick: {
                distance: -15, // Ticks inside
                splitNumber: 10,
                lineStyle: {
                    width: 1,
                    color: '#999'
                }
            },
            splitLine: { show: false }, // Hide split lines
            axisLabel: { show: false }, // Hide labels
            anchor: { show: false },
            title: { show: false },
            detail: {
                valueAnimation: true,
                fontSize: 18,
                fontWeight: 'bold',
                offsetCenter: [0, '0%'],
                color: '#2AF598',
                formatter: '{value}%'
            },
            data: [
                { value: value }
            ]
        }
    ]
});

const lineBarChartOption = computed(() => {
  // Generate more complex mock data for the right chart
  const count = 50;
  const categoryData = Array.from({ length: count }, (_, i) => 266 + i * (4400 - 266) / count);
  const coilingTemp = Array.from({ length: count }, (_, i) => parseFloat((890 + Math.sin(i / 5) * 5 + (Math.random() - 0.5) * 10).toFixed(1)));
  const finishingTemp = Array.from({ length: count }, (_, i) => parseFloat((900 + Math.cos(i / 6) * 8 + (Math.random() - 0.5) * 12).toFixed(1)));
  const rollShift = Array.from({ length: count }, (_, i) => parseFloat(((i % 10) * 5 + Math.random() * 10).toFixed(1)));
  const forceDiff = Array.from({ length: count }, (_, i) => parseFloat(((i % 7) * 8 + Math.random() * 15).toFixed(1)));
  const iuAvg = Array.from({ length: count }, (_, i) => parseFloat((126.84 + Math.sin(i / 3) * 0.005 + (Math.random() - 0.5) * 0.008).toFixed(3)));
  const iuDiff = Array.from({ length: count }, (_, ) => parseFloat(((Math.random() - 0.5) * 0.01).toFixed(3)));
  const secondaryFactor = Array.from({ length: count }, (_, ) => parseFloat((750 + Math.random() * 100).toFixed(1))); // Example bar data

  return {
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'cross',
            crossStyle: { color: '#999' }
        }
    },
    legend: {
        data: ['热轧卷取温度', '热轧终轧温度', '3机架上中间辊窜辊实际', 'S2机架轧制力差DS-OS', 'IU均值', 'IU差值', '二次项系数'],
        textStyle: { color: '#c0c4cc' },
        top: 10
    },
    grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true },
    xAxis: [
        {
            type: 'category',
            data: categoryData,
            axisPointer: { type: 'shadow' },
            axisLabel: { color: '#c0c4cc' },
            name: '(m)',
            nameLocation: 'end',
            nameTextStyle: { color: '#c0c4cc', align: 'right', verticalAlign: 'top', padding: [25, 0, 0, 0] } 
        }
    ],
    yAxis: [
        {
            type: 'value',
            name: '温度 (℃)',
            min: 700,
            max: 950,
            position: 'left',
            axisLine: { show: true, lineStyle: { color: '#e6a23c' } },
            axisLabel: { formatter: '{value}', color: '#e6a23c' },
            splitLine: { lineStyle: { color: '#3a5a8a' } }
        },
        {
            type: 'value',
            name: 'IU/系数',
            min: 126.83,
            max: 126.85, // Adjust range based on data
            position: 'right',
            axisLine: { show: true, lineStyle: { color: '#5470c6' } },
            axisLabel: { formatter: '{value}', color: '#5470c6' },
             splitLine: { show: false } // Hide grid for this axis
        },
         {
            type: 'value',
            name: '力/位移', // Example for other series
            position: 'right',
            offset: 80, // Offset further right
            axisLine: { show: true, lineStyle: { color: '#91cc75' } },
            axisLabel: { formatter: '{value}', color: '#91cc75' },
             splitLine: { show: false }
        }
    ],
     dataZoom: [
        { type: 'inside', start: 0, end: 100 },
        { start: 0, end: 100, handleIcon: '...', /* Use same handleIcon as QualityJudge */ textStyle: { color: '#c0c4cc' }, borderColor: '#3a5a8a' }
    ],
    series: [
        { name: '热轧卷取温度', type: 'line', yAxisIndex: 0, data: coilingTemp, itemStyle: { color: '#e6a23c' } , showSymbol: false, smooth: true },
        { name: '热轧终轧温度', type: 'line', yAxisIndex: 0, data: finishingTemp, itemStyle: { color: '#fab139' }, showSymbol: false, smooth: true },
        { name: '3机架上中间辊窜辊实际', type: 'line', yAxisIndex: 2, data: rollShift, itemStyle: { color: '#91cc75' }, showSymbol: false, smooth: true }, // Example assignment to 3rd yAxis
        { name: 'S2机架轧制力差DS-OS', type: 'line', yAxisIndex: 2, data: forceDiff, itemStyle: { color: '#73c0de' }, showSymbol: false, smooth: true }, // Example assignment to 3rd yAxis
        { name: 'IU均值', type: 'line', yAxisIndex: 1, data: iuAvg, itemStyle: { color: '#5470c6' }, showSymbol: false, smooth: true },
        { name: 'IU差值', type: 'line', yAxisIndex: 1, data: iuDiff, itemStyle: { color: '#fac858' }, showSymbol: false, smooth: true },
        { name: '二次项系数', type: 'bar', yAxisIndex: 0, data: secondaryFactor, itemStyle: { color: '#3ba272', opacity: 0.6 }, barWidth: '60%' } // Example bar series
    ]
  };
});

// --- ECharts Init & Update --- 
const initCharts = () => {
  gaugeInstances = [];
  const refs = [gaugeChart1Ref, gaugeChart2Ref, gaugeChart3Ref, gaugeChart4Ref, gaugeChart5Ref, gaugeChart6Ref, gaugeChart7Ref, gaugeChart8Ref];
  const values = [...gaugeValuesLeft.value, ...gaugeValuesRight.value];
  
  refs.forEach((ref, index) => {
     try {
      if (ref.value) {
        const chart = echarts.init(ref.value);
        chart.setOption(createGaugeOption(values[index]));
        gaugeInstances.push(chart);
      }
     } catch (error) {
       console.error(`Gauge chart ${index+1} initialization failed:`, error);
     }
  });

   try {
      if (lineBarChartRef.value && !lineBarChartInstance) {
        lineBarChartInstance = echarts.init(lineBarChartRef.value);
        lineBarChartInstance.setOption(lineBarChartOption.value);
      }
   } catch (error) {
      console.error("Line/Bar chart initialization failed:", error);
   }
};

const resizeCharts = () => {
  gaugeInstances.forEach(chart => chart?.resize());
  lineBarChartInstance?.resize();
};

// --- Lifecycle Hooks --- 
onMounted(() => {
  // Ensure DOM is ready for ECharts
  nextTick(initCharts);
  window.addEventListener('resize', resizeCharts);
});

onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts);
  gaugeInstances.forEach(chart => chart?.dispose());
  lineBarChartInstance?.dispose();
});

// Placeholder handlers
// const handleSearch = () => {};
// const handleReset = () => {};

</script>

<style scoped>
/* --- Base Styles --- */
.statistics-container {
  background-color: #0a1a3a;
  color: #c0c4cc;
  padding: 15px;
  height: 100%; 
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', 'Segoe UI', sans-serif;
  font-size: 13px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* --- Header Section --- */
.header-section {
  background-color: #1c2d5a;
  padding: 10px 15px;
  border-radius: 3px;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.roll-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.roll-label {
  margin-right: 8px;
  white-space: nowrap;
}

:deep(.roll-input .el-input__wrapper) {
   height: 28px;
  line-height: 28px;
  background-color: #0a1a3a !important;
  border: 1px solid #3a5a8a !important;
  border-radius: 3px !important;
  color: #c0c4cc !important;
  box-shadow: none !important;
  font-size: 13px !important;
  width: 150px;
}
:deep(.roll-input .el-input__inner) {
   color: #c0c4cc !important;
  height: 26px !important;
  line-height: 26px !important;
}

.analysis-btn {
  width: 100px;
  height: 28px;
  padding: 0 15px;
  border: none;
  border-radius: 3px;
  font-size: 13px;
  cursor: pointer;
  margin-left: 10px;
  color: #fff;
  background-color: #2979ff;
}
.analysis-btn:hover { background-color: #5393ff; }

:deep(.analysis-tabs .el-tabs__header) {
   margin: 0;
}

:deep(.analysis-tabs .el-tabs__nav-wrap::after) {
  background-color: #3a5a8a; 
}

:deep(.analysis-tabs .el-tabs__item) {
  color: #c0c4cc;
  height: 35px; 
  line-height: 35px;
  font-size: 14px;
}
:deep(.analysis-tabs .el-tabs__item.is-active) {
  color: #409eff;
}
:deep(.analysis-tabs .el-tabs__active-bar) {
  background-color: #409eff;
}

/* --- Main Content --- */
.main-content {
  flex-grow: 1;
  min-height: 0;
  display: flex;
  gap: 15px;
}

.main-content-placeholder {
   flex-grow: 1;
   display: flex;
   align-items: center;
   justify-content: center;
   color: #5a7aa4;
}

/* --- Panels --- */
.panel {
  background-color: #1c2d5a;
  border: 1px solid #3a5a8a;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden; /* Prevent content overflow */
  position: relative; /* For decorative borders */
}

.left-panel { flex-basis: 45%; } /* Adjust flex-basis as needed */
.right-panel { flex-basis: 55%; }

/* --- Decorative Borders --- */
.panel::before, .panel::after {
  content: '';
  position: absolute;
  width: 10px;
  height: 10px;
  border-color: #409eff; /* Highlight color */
  border-style: solid;
}
.panel::before {
  top: -1px;
  left: -1px;
  border-width: 2px 0 0 2px;
  border-top-left-radius: 4px;
}
.panel::after {
  top: -1px;
  right: -1px;
  border-width: 2px 2px 0 0;
   border-top-right-radius: 4px;
}
.panel > .panel-body::before, .panel > .panel-body::after {
   content: '';
  position: absolute;
  width: 10px;
  height: 10px;
  border-color: #409eff; 
  border-style: solid;
}
.panel > .panel-body::before {
  bottom: -1px;
  left: -1px;
  border-width: 0 0 2px 2px;
   border-bottom-left-radius: 4px;
}
.panel > .panel-body::after {
  bottom: -1px;
  right: -1px;
  border-width: 0 2px 2px 0;
   border-bottom-right-radius: 4px;
}


.panel-header {
  padding: 8px 15px;
  background-color: rgba(41, 121, 255, 0.1); /* Slightly lighter blue header */
  border-bottom: 1px solid #3a5a8a;
  text-align: center;
  flex-shrink: 0;
}

.panel-title {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}

.panel-subtitle {
  font-size: 13px;
  color: #c0c4cc;
  margin-left: 10px;
}

.panel-body {
  padding: 15px;
  flex-grow: 1;
  min-height: 0;
  overflow-y: auto; /* Allow vertical scroll within panel body */
   scrollbar-width: thin;
  scrollbar-color: #3a5a8a #142a52;
  position: relative; /* Needed for pseudo-elements */
}

.panel-body::-webkit-scrollbar { width: 6px; }
.panel-body::-webkit-scrollbar-track { background: #142a52; border-radius: 3px; }
.panel-body::-webkit-scrollbar-thumb { background-color: #3a5a8a; border-radius: 3px; }


/* Left Panel Specific */
.gauge-charts-row {
  display: flex;
  justify-content: space-around; /* Distribute charts */
  margin-bottom: 15px;
}

.gauge-chart-container {
  width: 23%; /* Adjust width */
  height: 120px; /* Adjust height */
}

.reason-text {
  background-color: #0f2142; /* Darker background for text */
  padding: 8px 12px;
  border-radius: 3px;
  margin-bottom: 15px;
  font-size: 12px;
  line-height: 1.5;
}
.reason-label { font-weight: bold; margin-right: 5px; }

/* Right Panel Specific */
.chart-container-large {
  flex-grow: 1; /* Take remaining space */
  min-height: 300px; /* Ensure enough height */
}

/* --- Shared Table Styles --- */
:deep(.el-table) { background-color: transparent; --el-table-border-color: #3a5a8a; --el-table-header-bg-color: #2a5caa; --el-table-header-text-color: #fff; --el-table-tr-bg-color: #0f2142; --el-table-row-hover-bg-color: #183153; --el-table-text-color: #c0c4cc; --el-table-border: 1px solid #3a5a8a; }
:deep(.el-table th.el-table__cell) { background-color: var(--el-table-header-bg-color) !important; color: var(--el-table-header-text-color); padding: 6px 8px !important; font-weight: normal; border-color: #3a5a8a !important; }
:deep(.el-table td.el-table__cell) { padding: 6px 8px !important; border-color: #3a5a8a !important; background-color: #0f2142 !important; }
:deep(.el-table--border .el-table__inner-wrapper::after), :deep(.el-table--border::after), :deep(.el-table--border::before), :deep(.el-table__inner-wrapper::before) { background-color: #3a5a8a; }
:deep(.el-table .el-table__cell) { text-align: center; }

</style>
